var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen('8001');
console.log('running 8001');
var bmpBuffer = fs.readFileSync('images/img-1.jpg');
console.dir(bmpBuffer);
console.log("test images");
function handler (req, res) {
	console.log(__dirname);
  fs.readFile(__dirname + '/index2.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index2.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

var usernames = {};
var images={};

var rooms = ['192.168.1.16', 'room2', 'room3'];//192.168.1.126


io.sockets.on('connection', function (socket) {

	// when the client emits 'sendchat', this listens and executes
	socket.on('sendchat', function (data) {
		// we tell the client to execute 'updatechat' with 2 parameters
		io.sockets.emit('updatechat', socket.username, data);
		process.on('connection', function (err) {
		console.log('lang nghe connection: ' + err);
		});
	
	});
	

	socket.on('changeimage', function (data) {
		// we tell the client to execute 'updatechat' with 2 parameters
		images[socket.username] = data;
		io.sockets.emit('updateimage', socket.username, data);
	});


	// when the client emits 'adduser', this listens and executes
	socket.on('adduser', function(username,domain){
		// we store the username in the socket session for this client
		socket.username = username;
		// add the client's username to the global list
		usernames[username] = username;
		socket.room =domain;
		socket.join(domain);
		
		// echo to client they've connected
		socket.emit('updatechat', 'SERVER', 'you have connected');
		console.log(domain);
		// echo globally (all clients) that a person has connected
		//socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
		socket.broadcast.to(domain).emit('updatechat', 'SERVER', username + ' has connected to this room');
		// update the list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
		io.sockets.emit('updateimageall', images);
	});

	// when the user disconnects.. perform this
	socket.on('disconnect', function(){
		// remove the username from global usernames list
		delete usernames[socket.username];
		delete images[socket.username];
		// update list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
		io.sockets.emit('updateimageall', images);
		// echo globally that this client has left
		socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
	});
})
